package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.system.api.domain.SysLogininfor;
import com.ruoyi.system.mapper.SysLogininforMapper;
import com.ruoyi.system.service.ISysLogininforService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author ruoyi
 */
@Service
public class SysLogininforServiceImpl implements ISysLogininforService {

    @Autowired
    private SysLogininforMapper logininforMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     */
    @Override
    public int insertLogininfor(SysLogininfor logininfor) {
        if (logininfor.getInfoId() == null) {
            logininfor.setInfoId(Seq.getSeqId());
        }
        return logininforMapper.insertLogininfor(logininfor);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor) {
        return logininforMapper.selectLogininforList(logininfor);
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return 结果
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        return logininforMapper.deleteLogininforByIds(infoIds);
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        logininforMapper.cleanLogininfor();
    }

    @Override
    public String updateLocation(SysLogininfor sysLogininfor) {
        List<SysLogininfor> logininforList = jdbcTemplate.query("select info_id,ipaddr from sys_logininfor ", new BeanPropertyRowMapper<>(SysLogininfor.class));
        jdbcTemplate.batchUpdate("update sys_logininfor set ip_location = ? where info_id = ?", new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                SysLogininfor logininfor = logininforList.get(i);
                String realAddressByIP = com.ruoyi.common.utils.ip.AddressUtils.getRealAddressByIP(logininfor.getIpaddr());
                ps.setString(1, realAddressByIP);
                ps.setLong(2, logininfor.getInfoId());
            }
            @Override
            public int getBatchSize() {
                return logininforList.size();
            }
        });
        return "操作成功";
    }
}
